let Mockup = {
    proxy: [
        {enable:false, url:'/myself',                     mock:'/mock/myself.json'},
        {enable:true, url:'/user/statistic',             mock:'/mock/user/statistic.json'},
        {enable:true, url:'/user/course',                mock:'/mock/user/course.json'},

        {enable:true, url:'/resource/carousel',          mock:'/mock/resource/carousel.json'},

        {enable:true, url:'/course/detail',              mock:'/mock/course/detail.json'},
        {enable:true, url:'/course/hot',                 mock:'/mock/course/hot.json'},

        {enable:true, url:'/admin/user/list',            mock:'/mock/admin/user/list.json'},
        {enable:true, url:'/admin/course/list',          mock:'/mock/admin/course/list.json'},
        {enable:true, url:'/admin/course/student',       mock:'/mock/admin/course/student.json'},
        {enable:true, url:'/admin/resource/image',       mock:'/mock/admin/resource/image.json'},
        {enable:true, url:'/admin/resource/video',       mock:'/mock/admin/resource/video.json'},
        {enable:true, url:'/admin/resource/image/list',  mock:'/mock/admin/resource/imageList.json'},
        {enable:true, url:'/admin/resource/video/list',  mock:'/mock/admin/resource/videoList.json'},
    ],
    mock: function (url) {
        let arr = url.split('?');
        let path = arr[0];
        let param = arr[1] ? '?' + arr[1] : '';

        let match = this.proxy.filter(opt => opt.enable && path === opt.url) || [];
        return match.length === 1 && match[0] && (match[0].mock + param) || url;
    }
};

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

axios.interceptors.request.use(function (config) {

    //逐级遍历对象的属性，去除空格
    let trim = function (obj) {
        for (let key in obj) {
            if (obj[key] || obj[key] == 0) {
                if (typeof(obj[key]) === 'string') {
                    obj[key] = obj[key].trim();

                    //空字符串替换成null
                    if (obj[key] == '') {
                        delete obj[key];
                    }

                } else if (typeof(obj[key]) === 'object') {
                    trim(obj[key]);
                }
            } else {
                delete obj[key];
            }
        }
    };

    //提交数据前，去除首尾空格
    let data = config.params || config.data || {};
    trim(data);

    config.url = Mockup.mock(config.url);

    return config;
}, function (error) {
    return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
    if (response.status == '200') {
        let result = response.data || {};
        if (result.success) {
            return result;
        } else {
            //处理全局错误
            let errorMsg = response.data.msg;
            if (Vue && Vue.prototype.$message && errorMsg) {
                Vue.prototype.$message.error(errorMsg);
            }

            return Promise.reject(result);
        }
    }

}, function (err) {
    console.log(err);
    if (Vue && Vue.prototype.$message) {
        Vue.prototype.$message.error('调用后端接口失败，HTTP响应码为' + err.response.status + '，请求地址为：' + err.response.config.url);
    }
    return Promise.reject(err);
});


Date.prototype.format = function(format) {
    let o = {
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(), //day
        "h+" : this.getHours(), //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3), //quarter
        "S" : this.getMilliseconds() //millisecond
    }

    if(/(y+)/.test(format)) {
        format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }

    for(let k in o) {
        if(new RegExp("("+ k +")").test(format)) {
            format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    }

    return format;
};

Vue.use(function (Vue) {
    Vue.prototype.$request = function () {
        let request = {
            params: {},
            hash: {}
        };

        request.hash = window.location.hash.substring(1);

        let params = window.location.search.substring(1).split("&");
        for (let i = 0; i < params.length; i++) {
            let pair = params[i].split("=");
            if (pair.length === 2) {
                request.params[pair[0]] = pair[1];
            }
        }

        return request;
    }();

    Vue.mixin({
        methods: {
            $loadLoginUser: function () {
                let vue = this;

                let url = Mockup.mock('/myself');
                return axios.get(url).then(resp => {
                    vue.user = resp.data || {};
                    return resp.data;
                });
            }
        },
        filters: {
            date: function (value) {
                return new Date(value).format('yyyy-MM-dd');
            },
            datetime: function (value) {
                return new Date(value).format('yyyy-MM-dd hh:mm');
            },
            duration: function (value) {
                if (value > 3600 ) {
                    let hour = Math.floor(value / 3600);
                    let min = Math.floor((value - hour * 3600) / 60);
                    return `${hour}小时${min}分`;
                } else if (value > 60 ) {
                    let min = Math.floor(value / 60);
                    let sec = value - min * 60;
                    return `${mins}分${sec}秒`;
                } else {
                    return `${value}秒`
                }
            },
            size: function (value) {
                if (value > 1024 * 1024 * 1024) {
                    let g = (value / (1024 * 1024 * 1024)).toFixed(2);
                    return `${g}G`;
                } else if (value > 1024 * 1024) {
                    let m = (value / (1024 * 1024)).toFixed(2);
                    return `${m}M`;
                } else if (value > 1024) {
                    let k = (value / (1024)).toFixed(2);
                    return `${k}K`;
                } else {
                    return `${value}B`;
                }
            }
        }
    });
});
